﻿using System;
using System.Text;

namespace Development.Network.Msg
{
    public class MsgPacket
    {
        public int Lenth;            //包长
        public int MsgId;            //消息id
        public int UserId;           //用户id
        public int Status;          //预留字段
        public byte[] Data;          //数据部分

        public object UserToken;    //用户网络数据

        public MsgPacket()
        { }

        public MsgPacket(int msgId,int userId,int fillData,byte [] data)
        {
            this.MsgId = msgId;
            this.UserId = userId;
            this.Status = fillData;
            this.Data = data;
            Lenth = 0;
            UserToken = null;
        }

        public T GetToken<T>()
        {
            return (T)UserToken;
        }

        public override string ToString()
        {
            string dataString = Encoding.UTF8.GetString(Data);
            return string.Format("len={0},msgId={1},userId={2},status={3},data={4}", Lenth, MsgId, UserId, Status, dataString);
        }

        public static T PacketToObj<T>(MsgPacket msg) where T : MsgBase,new()
        {
            T t = new T();
            t.Unpack(msg);
            return t;
        }
        /// <summary>
        /// 拆包
        /// </summary>
        /// <returns></returns>
        public static MsgPacket SplitPacket(object userToken,byte [] buffer,int offset,int length)
        {
            MsgPacket packet = new MsgPacket();
            packet.Lenth = BitConverter.ToInt32(buffer, offset);
            packet.MsgId = BitConverter.ToInt32(buffer, offset + 4);
            packet.UserId = BitConverter.ToInt32(buffer, offset + 8);
            packet.Status= BitConverter.ToInt32(buffer, offset + 12);
            packet.UserToken = userToken;
            packet.Data = new byte[length - 16];
            Array.Copy(buffer, offset + 16, packet.Data, 0, length - 16);
            return packet;
        }

     
    }
}
